/**
 * 上传文件请求模块
 */
import request from '@/utils/request';

// 处理文件类型
export type FileType = 'image' | 'media' | 'file'

export interface FileResp {
  path: string
  m3u8?: string
  image?: string
}

// 上传文件
export const upload = (type: FileType, file: File, parm?: Record<string, any>, callBack?: Function) => {
  const param = new FormData()
  if (parm) {
    Reflect.ownKeys(parm).forEach((key: any) => {
      param.append(key, parm[key])
    });
  }
  param.append('file', file)
  return request<FileResp>({
      method: 'POST',
      data: param,
      url: `static/upload/${type}`,
      headers: {
        'Content-Type': 'multipart/form-data'
      }, onUploadProgress: (progressEvent) => { // 原生获取上传进度的事件
        if (callBack && progressEvent.lengthComputable) {
          // 属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量
          // 如果lengthComputable为false，就获取不到progressEvent.total和progressEvent.loaded
          callBack(progressEvent);
        }
      },
    }
  );
};

export const delFile = (type: FileType, path: String) => {
  return request({
      method: 'DELETE',
      url: `static/${type}?path=${path}`
    }
  );
};

